package com.wgchao.authmanager.application.filter;

import com.wgchao.authmanager.infrastructure.exception.TokenTypeException;
import com.wgchao.authmanager.infrastructure.token.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: DefaultTokenAuthentication
 * @author: wgchao
 * @createTime: 2020/5/12 5:09 PM
 * @Description: 默认身份验证方式-前台身份验证
 */
@Component
public class DefaultTokenAuthentication implements TokenAuthentication {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String authentication(String token, AuthMethod[] authMethods) {
        Claims claims = jwtUtil.parseJWT(token);
        if(contain(authMethods, AuthMethod.NORMAL) && claims.get("type").toString().equals("local")){//本地系统
            return claims.getId();
        }else{
            throw new TokenTypeException("身份令牌类型错误");
        }
    }

    private boolean contain(AuthMethod[] authMethods, AuthMethod authMethod){
        for(int i=0; i<authMethods.length; i++){
            if(authMethod.compareTo(authMethods[i]) == 0){
                return true;
            }
        }
        return false;
    }
}
